﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MethodWorx.CMS.Content;
using MethodWorx.CMS.Web;

namespace MethodWorx.CMS.TemplateLanguage.Parsers
{
    public class PageDescendantsParser : IParser
    {
        #region IParser Members

        public string[] Parameters { get { return new string[] { }; } }

        public object Parse(CmsRequestContext context, IEnumerable<object> stack, Dictionary<string, object> parameters)
        {
            var page = stack.OfType<MethodWorx.CMS.Content.Page>().FirstOrDefault();
            if (page == null)
                throw new Exception("No Page on the stack");

            var descendants = new List<MethodWorx.CMS.Content.Page>();

            this.GetChildren(descendants, page);

            //
            //  ok, return the pages
            return descendants.ToArray();
        }

        private void GetChildren(List<MethodWorx.CMS.Content.Page> descendants, MethodWorx.CMS.Content.Page page)
        {
            foreach (var child in page.ChildPages)
            {
                descendants.Add(child);
                this.GetChildren(descendants, child);
            }
        }

        public string Name
        {
            get { return "descendants"; }
        }

        public string Namespace
        {
            get { return "page"; }
        }

        #endregion
    }
}
